<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-04-08
 * Time: 14:29
 */
namespace app\admin\controller;
use Sunra\PhpSimple\HtmlDomParser;
use Think\Db;
use think\Exception;

class Commodity extends Base
{
    /**
     * 空操作
     */
    public function _empty(){
        if($this->check_admin_login()){
            $this->redirect('admin/Index/index');
        }else{
            $this->redirect('admin/login');
        }
    }

    /**
     * 好物列表
     */
    public function good_list(){
        $page_param = input('param.');
        if (isset($page_param['page']) && $page_param['page'] > 0)
            unset($page_param['page']);

        $carousel_list = Db::table('yf_good')->alias('a')->field('a.*,b.name')->join('yf_items_cate b','a.goodstype=b.id','LEFT')->order('a.good_id desc')->paginate(20, false, ['query' => $page_param]);
        //分页信息
        $page = $carousel_list->render();
        $carousel_list = $carousel_list->toArray();
        //模板变量赋值
        $this->assign('list', $carousel_list['data']);
        $this->assign('total', $carousel_list['total']);
        $this->assign('page', $page);
        // 渲染模板输出
        return $this->fetch();
    }



    //轮播排序
    public function good_order(){
        if (!$this->request->isPost()){
            return json(['code'=>0,'msg'=>'提交方式不正确']);
        }else{
            foreach ($_POST as $id => $sort){
                Db::name('good')->where(array('good_id' => $id ))->setField('sort' , $sort);
            }
            return json(['code'=>200,'msg'=>'排序更新成功']);
        }
    }

    /**
     * 轮播添加
     */
    public function good_add(){
        if ($this->request->isPost()){
            //开启事务
            Db::startTrans();
            try{
                $data['activity_type'] = input('param.activity_type/a','') == ''? '': implode(',',input('param.activity_type/a','')); //好物标题
                $data['title'] = input('param.title',''); //好物标题
                $data['price'] = input('param.price',0); //好物价格
                $data['itemid'] = input('param.itemid',0); //好物淘宝id
                if ($data['itemid'] != 0) {
                    $num = Db::table('yf_good')->where(['itemid' => $data['itemid']])->count();
                    if ($num > 0) {
                        throw new Exception('商品已存在，请误重复添加该商品');
                    }
                }
                $pics = input('param.itempic/a',''); //好物图片链接
                if (!empty($pics)){
                    $data['itempic'] = implode(',',$pics);
                }
                $data['desc'] = input('param.desc','');//好物推荐理由
                $data['begin_time'] = input('param.begin_time',0);//开始时间
                $data['end_time'] = input('param.end_time',0);//结束时间
                $data['shoptype'] = input('param.shoptype','C');//好物所属商店类型
                $data['goodstype'] = input('param.goodstype',0);//好物类型
                $data['sell_counter'] = input('param.sell_counter',0);//好物月销量
                $data['coupon'] = input('param.coupon',0);//是否有优惠券 0无 1有
                if ($data['coupon'] == 1){
                    $data['coupon_url'] = input('param.coupon_url','');//优惠券链接
                    $data['coupon_price'] = input('param.coupon_price',0);//优惠券金额
                    $data['itemendprice'] =  $data['price'] - $data['coupon_price'];//券后价
                }else{
                    $data['itemendprice'] =  $data['price'];
                }
                if ($data['price'] <  $data['coupon_price']){
                    throw new Exception('价格或者优惠券金额有误，请确认后重新上传');
                }
                if ($data['shoptype'] == ''){
                    throw new Exception('请选择天猫或者淘宝');
                }
                if ($data['goodstype'] == 0){
                    throw new Exception('商品类型未选择');
                }
                if ($data['coupon'] == 1 && (empty($data['coupon_url']) || empty($data['coupon_price']))){
                    throw new Exception('优惠券信息有误');
                }
                if ($data['begin_time'] == 0){
                    throw new Exception('开始时间不能为空');
                }
                if ($data['end_time'] == 0){
                    throw new Exception('结束时间不能为空');
                }
                $data['begin_time'] = date_to_unixtime( $data['begin_time']);
                $data['end_time'] = date_to_unixtime( $data['end_time']);
                $data['add_time'] = time();//结束时间
                $data['sort'] = 50;//排序
                $data['admin_author'] = session('admin_auth.aid');//发布者
                Db::table('yf_good')->insert($data);
                //事务提交
                Db::commit();
                return json(['code'=>200,'msg'=>'success']);
            }catch (Exception $e){
                //事务回滚
                Db::rollback();
                return json(['code'=>0,'msg'=>$e->getMessage()]);
            }
        }else{
            $items_cate = Db::name('items_cate')->field('id,name')->select();
            $this->assign('cate',$items_cate);
            // 渲染模板输出
            return $this->fetch();
        }
    }


    /**
     * 好物编辑
     */
    public function good_edit(){
        if ($this->request->isPost()){
            //开启事务
            Db::startTrans();
            try{
                $data['good_id'] = input('param.good_id',0); //好物id
                if ($data['good_id'] == 0){
                    throw new Exception('好物id未传');
                }
                $data['activity_type'] = input('param.activity_type/a','') == ''? '': implode(',',input('param.activity_type/a','')); //好物标题
                $pics = input('param.itempic/a',''); //好物图片链接
                if (!empty($pics)){
                    $data['itempic'] = implode(',',$pics);
                }
                $data['title'] = input('param.title',''); //好物标题
                $data['price'] = input('param.price',0); //好物价格
                $data['itemid'] = input('param.itemid',0); //好物淘宝id
                $data['desc'] = input('param.desc','');//好物推荐理由
                $data['begin_time'] = input('param.begin_time',0);//开始时间
                $data['end_time'] = input('param.end_time',0);//结束时间
                $data['shoptype'] = input('param.shoptype','C');//好物所属商店类型
                $data['goodstype'] = input('param.goodstype',0);//好物类型
                $data['sell_counter'] = input('param.sell_counter',0);//好物月销量
                $data['coupon'] = input('param.coupon',0);//是否有优惠券 0无 1有
                if ($data['coupon'] == 1){
                    $data['coupon_url'] = input('param.coupon_url','');//优惠券链接
                    $data['coupon_price'] = input('param.coupon_price',0);//优惠券金额
                    $data['itemendprice'] =  $data['price'] - $data['coupon_price'];//券后价
                }else{
                    $data['itemendprice'] =  $data['price'];
                }
                if ($data['price'] <  $data['coupon_price']){
                    throw new Exception('价格或者优惠券金额有误，请确认后重新上传');
                }
                if ($data['shoptype'] == ''){
                    throw new Exception('请选择天猫或者淘宝');
                }
                if ($data['goodstype'] == 0){
                    throw new Exception('商品类型未选择');
                }
                if ($data['coupon'] == 1 && (empty($data['coupon_url']) || empty($data['coupon_price']))){
                    throw new Exception('优惠券信息有误');
                }
                if ($data['begin_time'] == 0){
                    throw new Exception('开始时间不能为空');
                }
                if ($data['end_time'] == 0){
                    throw new Exception('结束时间不能为空');
                }
                $data['begin_time'] = date_to_unixtime( $data['begin_time']);
                $data['end_time'] = date_to_unixtime( $data['end_time']);
                $data['add_time'] = time();//结束时间
                $data['sort'] = 50;//排序
                $data['admin_author'] = session('admin_auth.aid');//发布者
                Db::table('yf_good')->update($data);
                //事务提交
                Db::commit();
                return json(['code'=>200,'msg'=>'success']);
            }catch (Exception $e){
                //事务回滚
                Db::rollback();
                return json(['code'=>0,'msg'=>$e->getMessage()]);
            }
        }else{
            $good_info=Db::name('good')->where(array('good_id'=>input('good_id')))->find();
            $items_cate = Db::name('items_cate')->field('id,name')->select();
            $this->assign('cate',$items_cate);
            if ($good_info){
                $good_info['itempic'] = get_img_url($good_info['itempic']);
                $pic_list = explode(',',$good_info['itempic']);
                if (!empty($pic_list)){
                    foreach ($pic_list as $k=>$v){
                        if (!empty($v)){
                            $pic_list[$k] = get_img_url($v);
                        }else{
                            continue;
                        }
                    }
                }
            }
            $this->assign('data',$good_info);
            $this->assign('pic_list',$pic_list);
            // 渲染模板输出
            return $this->fetch();
        }
    }

    //好物删除
    public function good_del(){
        $good_id=input('good_id','','intval');
        Db::startTrans();
        try{
            if (!is_numeric($good_id)){
                throw new Exception('轮播id错误');
            }
            $rst=Db::name('good')->where('good_id',$good_id)->delete();
            if($rst!==false){
                Db::commit();
                return json(['code'=>200,'msg'=>'好物删除成功']);
            }else{
                throw new Exception('好物删除失败');
            }
        }catch (Exception $e){
            Db::rollback();
            return json(['code'=>0,'msg'=>$e->getMessage()]);
        }
    }

     //好物批量删除
    public function alldel(){
        $good_ids=input('param.arr/a','');
        if (empty($good_ids)){
            return json(['code'=>0,'msg'=>'请选择要删除的数据']);
        }
        Db::startTrans();
        try{

            $rst=Db::name('good')->where(['good_id'=>['in',$good_ids]])->delete();
            if($rst!==false){
                Db::commit();
                return json(['code'=>200,'msg'=>'好物删除成功']);
            }else{
                throw new Exception('好物删除失败');
            }
        }catch (Exception $e){
            Db::rollback();
            return json(['code'=>0,'msg'=>$e->getMessage()]);
        }
    }


    /**
     * 根据淘宝、天猫url一键获取商品信息
     */
    public function ajax_getiteminfo(){
        $item_url = input('param.item_url','');
        try{
            if (empty($item_url)){
                throw new Exception('商品链接不能为空!');
            }
            $data = [];
            $arr = parse_url($item_url);
            parse_str(@array_pop(explode('?', $item_url)), $a);
            $data['itemid'] = $a['id'];
            if ($arr['host'] == 'detail.tmall.com'){
                $data['shoptype'] = 'B';
            }else if ($arr['host'] == 'item.taobao.com'){
                $data['shoptype'] = 'C';
            }else{
                throw new Exception('所选商品非淘宝/天猫商品!');
            }
            $goods_info = Db::name('items')->field('itemtitle,itemdesc,itemprice,itemsale,itempic,couponurl,couponmoney,start_time,end_time')->where(['itemid'=>$data['itemid']])->find();
            $dom = HtmlDomParser::file_get_html($item_url);
            if ($goods_info){
                $data['title'] = $goods_info['itemtitle'];
                $data['price'] = $goods_info['itemprice'];
                $data['desc'] = $goods_info['itemdesc'];
                $data['sell_counter'] = $goods_info['itemsale'];
            }else{
                $data['title'] = mb_convert_encoding($dom->find('title',0)->innertext(), "UTF-8", "GBK");
                $data['price'] = '';
                $data['desc'] = '';
                $data['sell_counter'] = '';
            }
            if ($data['shoptype'] == 'B'){
                $img = $dom->find('#J_UlThumb', 0)->find('img');
                foreach ($img as $element){
                    $picture = 'http:' . mb_convert_encoding($element->src, "UTF-8", "GBK");//商品图片
                    $pic[] = str_replace('_60x60q90','_430x430q90',$picture);;
                }
//                $data['itempic'] = 'http:'.mb_convert_encoding($dom->find('#J_UlThumb',0)->find('li',-1)->find('img',0)->src, "UTF-8", "GBK");//商品图片
//                if (!empty($data['itempic'])){
//                    $data['itempic'] = str_replace('_60x60q90','_430x430q90',$data['itempic']);
//                }else{
//                    $data['itempic'] = 'http:'.mb_convert_encoding($dom->find('#J_ImgBooth',0)->src, "UTF-8", "GBK");//商品图片
//                }
//                $data['itempic'] = 'http:'.mb_convert_encoding($dom->find('#J_ImgBooth',0)->src, "UTF-8", "GBK");//商品图片
            }else{
                $img = $dom->find('#J_UlThumb',0)->find('img');
                foreach ($img as $element){
                    $picture = 'http:' . mb_convert_encoding($element->getAttribute('data-src'), "UTF-8", "GBK");//商品图片
                    $pic[] = str_replace('_50x50','_400x400',$picture);
                }

//                $data['itempic'] = mb_convert_encoding($dom->find('#J_UlThumb',0)->find('li',-1)->find('img',0)->getAttribute('data-src'), "UTF-8", "GBK");//商品图片
//                if (!empty($data['itempic'])){
//                    $data['itempic'] = str_replace('_50x50','_400x400',$data['itempic']);
//                }else{
//                    $data['itempic'] = 'http:'.mb_convert_encoding($dom->find('#J_ImgBooth',0)->src, "UTF-8", "GBK");//商品图片
//                }
//                $data['itempic'] = 'http:'.mb_convert_encoding($dom->find('#J_ImgBooth',0)->src, "UTF-8", "GBK");//商品图片
            }
            $data['itempic'] = $pic;
            return json(['code'=>200,'msg'=>'success','data'=>$data]);
        }catch (Exception $e){
            return json(['code'=>0,'msg'=>$e->getMessage()]);
        }

    }

    public function small_images($itemid){
        $url = 'http://demo2.b2ef.cn/index.php?g=wap&m=detail&r=small_images&goods_id='.$itemid;//淘客基地
        $small_images = file_get_contents($url);
        $list = json_decode($small_images,true);
        foreach ($list['data'] as $k=>$v){
            $pic[] = $v['img'];
        }
        return $pic;
    }


}